import { ref, computed, unref, watch } from "vue";
import ProgressBar from "./progress-bar.vue";
import { debounce } from "lodash-es";

export let percentKey = Symbol("percent");
export let showKey = Symbol("show");

function customInterval(callback) {
  setTimeout(() => {
    if (callback() !== false) {
      customInterval(callback);
    }
  }, Math.random() * 200);
}
export default {
  install: (app) => {
    let startNum = ref(0);
    let endNum = ref(0);
    //真实进度
    let percent = computed(() => {
      // let unendNum = unref(endNum);
      let unstartNum = unref(startNum);
      if (unstartNum === 0) return 100;
      return 0; //(unendNum / unstartNum) * 100;
    });
    //是否显示
    let showDebounce = debounce((newStartNum) => {
      show.value = newStartNum !== 0;
    }, 200);
    let show = ref(false);
    watch(startNum, showDebounce);
    // let show = computed(() => unref(startNum) !== 0);
    // let show = computed(() => unref(percent) !== 0 && unref(percent) !== 100);

    //自增的值
    let maxPercent = 90;
    let autoIncrement = ref(0);
    // let timer;
    watch(show, (newShow) => {
      if (newShow) {
        customInterval(() => {
          if (autoIncrement.value > maxPercent) return false;
          if (show.value) {
            autoIncrement.value += Math.random();
          } else {
            return false;
          }
        });
      } else {
        autoIncrement.value = 0;
      }
      // if (newShow) {
      //   timer = setInterval(() => {
      //     autoIncrement.value += Math.random();
      //   }, 200);
      // } else {
      //   clearInterval(timer);
      //   autoIncrement.value = 0;
      // }
    });
    //用于展示的进度
    let fakePercent = computed(() => {
      let unpercent = unref(percent);
      let unautoIncrement = unref(autoIncrement);
      let fp = unpercent + unautoIncrement;
      //真实值是100就返回100
      if (unpercent === 100) {
        return unpercent;
      }
      //否则返回处理后的值
      return Math.min(fp, maxPercent);
    });
    app.provide(percentKey, fakePercent);
    app.provide(showKey, show);
    app.component("progress-bar", ProgressBar);
    app.config.globalProperties.$progressBar = {
      start() {
        startNum.value++;
      },
      end() {
        endNum.value++;
        if (startNum.value <= endNum.value) {
          startNum.value = 0;
          endNum.value = 0;
        }
      },
    };
  },
};
